﻿using Connection.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Connection.Presenter
{
    [Serializable()]
    public class ChatPresenter : MarshalByRefObject
    {
        ConversationModel _converModel = new ConversationModel();
        ConversationDetailModel _converDetailModel = new ConversationDetailModel();
        UserDB _userDB = new UserDB();

        public void StartConversation(string _username1, string _username2)
        {
            ConversationDetailDB _converDetailDB = new ConversationDetailDB();
            _converDetailModel.UserId1 = _userDB.SelectUserId(_username1);
            _converDetailModel.UserId2 = _userDB.SelectUserId(_username2);
            if (_converDetailDB.SelectConversationId(_converDetailModel.UserId1, _converDetailModel.UserId2) == null)
            {
                _converDetailModel.ConversationId = _converDetailDB.GenerateConversationId();
                _converDetailModel.AddNewConversation();
            }
            else
                _converDetailModel.ConversationId = _converDetailDB.SelectConversationId(_converDetailModel.UserId1, _converDetailModel.UserId2);
        }

        public void AddNewMessage(string _message, string _fromUsername)
        {
            _converModel.FromUserId = _userDB.SelectUserId(_fromUsername);
            _converModel.Message = _message;
            _converModel.TimeMess = DateTime.Now;
            _converModel.ConversationId = _converDetailModel.ConversationId;
            _converModel.AddNewMessConversation();
        }

        public string ShowChat(string _username1, string _username2)
        {
            ConversationDB _converDB = new ConversationDB();
            StartConversation(_username1, _username2);
            return String.Join(Environment.NewLine, _converDB.SelectAllConversationDisplay(_converDetailModel.ConversationId));
        }

        public int Test() { return 0; }
    }
}
